package com.artqiyi.dollmachine.views.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.artqiyi.artqiyisdk.common.constant.ArtqiyiConstant;
import com.artqiyi.artqiyisdk.utils.manager.ArtqiyiCommandManager;
import com.artqiyi.artqiyisdk.utils.manager.ArtqiyiPlayManager;
import com.artqiyi.dollmachine.R;
import com.artqiyi.dollmachine.common.Base.BaseActivity;
import com.artqiyi.dollmachine.common.constant.Constant;
import com.artqiyi.dollmachine.model.entity.CoinBuyBean;
import com.artqiyi.dollmachine.model.entity.DollBean;
import com.artqiyi.dollmachine.model.entity.DollDetailBean;
import com.artqiyi.dollmachine.model.entity.GameRecordBean;
import com.artqiyi.dollmachine.model.entity.NextPlayerBean;
import com.artqiyi.dollmachine.model.entity.SocketDeviceStatusBean;
import com.artqiyi.dollmachine.model.entity.SocketOnLookerBean;
import com.artqiyi.dollmachine.model.entity.UserInfoBean;
import com.artqiyi.dollmachine.presenter.DollOperatePresenter;
import com.artqiyi.dollmachine.presenter.base.PresenterCallbackCollection;
import com.artqiyi.dollmachine.utils.JSONUtils;
import com.artqiyi.dollmachine.utils.Rx2Timer;
import com.artqiyi.dollmachine.utils.ViewClickUtil;
import com.artqiyi.dollmachine.utils.manager.ConfigManager;
import com.artqiyi.dollmachine.utils.manager.MediaManager;
import com.artqiyi.dollmachine.utils.manager.PayDialogManager;
import com.artqiyi.dollmachine.utils.manager.UserInfoManager;
import com.artqiyi.dollmachine.utils.respone.GameResultRespone;
import com.artqiyi.dollmachine.views.widget.ToolBarView;
import com.artqiyi.dollmachine.views.widget.dialog.RxDialogList;
import com.artqiyi.dollmachine.views.widget.dialog.RxDialogNormal;
import com.artqiyi.dollmachine.views.widget.dialog.RxDialogPay;
import com.artqiyi.dollmachine.views.widget.dialog.RxDialogSureCancel;
import com.artqiyi.dollmachine.views.widget.dialog.RxDialogTurn;
import com.bumptech.glide.Glide;
import com.tencent.livesdk.ILVLiveManager;
import com.tencent.rtmp.ui.TXCloudVideoView;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import timber.log.Timber;

/**
 * Created by Administrator on 2017/10/31 0031.
 */
public class DollOperateActivity extends BaseActivity<DollOperatePresenter> implements View.OnClickListener, PresenterCallbackCollection.DollOperateActivityCallBack, View.OnTouchListener {
    @Bind(R.id.btnDone)
    Button mBtnDone;
    @Bind(R.id.btnSwitch)
    Button mBtnSwitch;
    @Bind(R.id.btnStart)
    Button mBtnStart;
    @Bind(R.id.btnAppointment)
    Button mBtnAppointment;
    @Bind(R.id.btnQueuing)
    Button mBtnQueuing;
    @Bind(R.id.btnDetail)
    ImageView mBtnDetail;
    @Bind(R.id.imageCoin)
    ImageView mImageCoin;
    @Bind(R.id.imageSound)
    ImageView imageSound;
    @Bind(R.id.imageReadyGo)
    ImageView mImageReadyGo;
    @Bind(R.id.startLayout)
    LinearLayout startLayout;
    @Bind(R.id.operateLayout)
    LinearLayout operateLayout;
    @Bind(R.id.onLookerLayout)
    LinearLayout onLookerLayout;

    @Bind(R.id.btnUp)
    Button mBtnUp;
    @Bind(R.id.btnLeft)
    Button mBtnLeft;
    @Bind(R.id.btnDown)
    Button mBtnDown;
    @Bind(R.id.btnRight)
    Button mBtnRight;

    @Bind(R.id.addBtn)
    Button addBtn;
    @Bind(R.id.progressLayout)
    LinearLayout progressLayout;
    @Bind(R.id.tvTime)
    TextView tvTime;
    @Bind(R.id.tvPeopleNum)
    TextView tvPeopleNum;

    @Bind(R.id.tvCoin)
    TextView tvCoin;
    @Bind(R.id.avatarImage)
    ImageView avatarImage;
    @Bind(R.id.avatarImage1)
    ImageView avatarImage1;
    @Bind(R.id.avatarImage2)
    ImageView avatarImage2;
    @Bind(R.id.avatarImage3)
    ImageView avatarImage3;
    @Bind(R.id.tvUserName)
    TextView tvUserName;
    @Bind(R.id.avatarLayout)
    LinearLayout avatarLayout;
    @Bind(R.id.liveVideoViewFront)
    TXCloudVideoView mLiveVideoViewFont;
    @Bind(R.id.liveVideoViewSide)
    TXCloudVideoView mLiveVideoViewSide;
    @Bind(R.id.onLookerVideoViewFront)
    TXCloudVideoView mOnLookerVideoViewFront;
    @Bind(R.id.onLookerVideoViewSide)
    TXCloudVideoView mOnLookerVideoViewSide;
    @Bind(R.id.onLookerVideoLayout)
    RelativeLayout mOnLookerVideoLayout;
    @Bind(R.id.onLiveVideoLayout)
    RelativeLayout mLiveVideoLayout;

    private DollBean mDollBean;
    private Rx2Timer countDownTimer;    //倒计时
    private DollDetailBean mDollDetailBean;
    private int mGameRecordId;

    private Socket mSocket;
    private boolean hasNextGamePlayerSubscribe = false;
    private boolean isSoundOn = true;
    private boolean isDetailDialogShow;
    private int mRequestCode = 100;

    private MediaManager mMediaManager;

    private AnimationDrawable mAnimationDrawable;

    private boolean isSwitch = false;                       //玩家模式是否切换,默认是围观
    private boolean isGameStart = false;                    //判断游戏是否已经开始，开始后，不能退出房间
    private boolean isCommandAble = false;                   //是否能发送指令

    private boolean isOnlookMode = true;                    //是否围观者模式，默认是围观者模式

    private ArtqiyiPlayManager mArtqiyiPlayManager;

    private ArtqiyiCommandManager mArtqiyiCommandManager;

    @Override
    public DollOperatePresenter getPresenter() {
        return new DollOperatePresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_dolloperate;
    }

    @Override
    protected void handleIntent(Intent intent) {
        super.handleIntent(intent);
        mDollBean = (DollBean) getIntent().getSerializableExtra(Constant.KEY_DOLLBEAN);
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mArtqiyiPlayManager = new ArtqiyiPlayManager(DollOperateActivity.this);
        mArtqiyiCommandManager = new ArtqiyiCommandManager();
        mArtqiyiPlayManager.init();
        mArtqiyiCommandManager.init();
        mBtnUp.setOnTouchListener(this);
        mBtnLeft.setOnTouchListener(this);
        mBtnDown.setOnTouchListener(this);
        mBtnRight.setOnTouchListener(this);
        mMediaManager = new MediaManager();
        mBtnDone.setOnClickListener(this);
        mBtnSwitch.setOnClickListener(this);
        addBtn.setOnClickListener(this);
        mBtnStart.setOnClickListener(this);
        mImageCoin.setOnClickListener(this);
        mBtnQueuing.setOnClickListener(this);
        mBtnDetail.setOnClickListener(this);
        mBtnAppointment.setOnClickListener(this);
        imageSound.setOnClickListener(this);

    }

    @Override
    protected void handleToolBar(ToolBarView toolBar) {
        super.handleToolBar(toolBar);
        toolBar.setBackPressed(DollOperateActivity.this);
    }

    @Override
    public void loadData() {
        super.loadData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDollDetail();
                setLongConnect();
                if (null != mMediaManager) mMediaManager.start();
            }
        }).start();
        if (null != mDollBean) joinRoom(mDollBean.getRoom_id());
    }

    private void setLongConnect() {
        try {
            Timber.d("Socket_server_host:" + ConfigManager.getInstance().getConfigBean().getSocket_server_host());
            mSocket = IO.socket(ConfigManager.getInstance().getConfigBean().getSocket_server_host());  // 创建Socket.IO长连接对象,地址是服务器返回来的
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        mSocket.on(Socket.EVENT_CONNECT, onConnect);
        mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectTimeout);
        mSocket.on("machine.status.changed", onDeviceStatusChange);     //设备状态改变事件
        mSocket.on("spectators.changed", onLookerChange);               //围观者改变事件
        mSocket.on("game.next.turn", onNextGamePlayer);               //下一局游戏玩家事件

        mSocket.connect();  // 连接socket
        handleSubscribeOrUnsubscribe(Constant.CHANNEL_EVENT_TYPE_SUBSCRIBE, "machines." + mDollBean.getId());                                //订阅设备状态改变事件
        handleSubscribeOrUnsubscribe(Constant.CHANNEL_EVENT_TYPE_SUBSCRIBE, "presence-machines." + mDollBean.getId() + ".spectators");       //订阅围观者改变事件
    }

    /*订阅或取消订阅后台定义的事件*/
    private void handleSubscribeOrUnsubscribe(String type, String channelEvent) {
        try {
            JSONObject object = new JSONObject();
            object.put("channel", channelEvent);
            object.put("auth", getToken());
            if (mSocket != null) mSocket.emit(type, object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //订阅或取消排队
    private void dolNextGamePlayerEventSubscribe(boolean isSubscribe) {
        if (isSubscribe) {
            //判断是否已经订阅
            if (!hasNextGamePlayerSubscribe) {
                hasNextGamePlayerSubscribe = true;
                handleSubscribeOrUnsubscribe(Constant.CHANNEL_EVENT_TYPE_SUBSCRIBE, "presence-machines." + mDollBean.getId() + ".player_queue");
                Timber.d("订阅成功");
            }
        } else {
            hasNextGamePlayerSubscribe = false;
            handleSubscribeOrUnsubscribe(Constant.CHANNEL_EVENT_TYPE_UNSUBSCRIBE, "presence-machines." + mDollBean.getId() + ".player_queue");
            Timber.d("取消订阅成功");
        }
    }

    private JSONObject getToken() throws JSONException {
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        jsonObject1.put("Authorization", UserInfoManager.getInstance().getUserInfoBean().getApi_token());
        jsonObject2.put("headers", jsonObject1);
        return jsonObject2;
    }

    private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Timber.d("连接成功");
            if (null != mDollBean)
                mPresenter.enterOrExitRoom(mDollBean.getId(), Constant.GAME_ACTION_ENTER);
        }
    };
    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Timber.d("断开连接");
        }
    };
    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Timber.d("连接失败");
        }
    };
    private Emitter.Listener onConnectTimeout = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Timber.d("连接成超时");
        }
    };
    private Emitter.Listener onDeviceStatusChange = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (args != null && args[1] != null) {
                        Timber.d("设备状态改变" + args[1]);
                        SocketDeviceStatusBean bean = JSONUtils.jsonString2Bean(String.valueOf(args[1]), SocketDeviceStatusBean.class);
                        handleOnDeviceStatusChange(bean);
                    }
                }
            });
        }
    };
    private Emitter.Listener onLookerChange = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (args != null && args[1] != null) {
                        Timber.d("围观者改变" + args[1]);
                        SocketOnLookerBean bean = JSONUtils.jsonString2Bean(String.valueOf(args[1]), SocketOnLookerBean.class);
                        handleOnLookerChange(bean);
                    }
                }
            });
        }
    };
    private Emitter.Listener onNextGamePlayer = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (args != null && args[1] != null) {
                        NextPlayerBean bean = JSONUtils.jsonString2Bean(String.valueOf(args[1]), NextPlayerBean.class);
                        handleNextPlayer(bean);
                    }
                }
            });
        }
    };

    private void handleNextPlayer(NextPlayerBean bean) {
        if (isFinishing()) return;
        UserInfoBean userInfoBean = UserInfoManager.getInstance().getUserInfoBean();
        if (userInfoBean != null) {
            if (userInfoBean.getId() == bean.getUser_id()) {
                //轮到自己
                doTurnDialog();
                mBtnQueuing.setVisibility(View.GONE);
            }
        }
    }

    private void doTurnDialog() {
        RxDialogTurn rxDialogTurn = new RxDialogTurn(DollOperateActivity.this);//提示弹窗
        rxDialogTurn.setCountDown();
        rxDialogTurn.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mDollDetailBean) mPresenter.startDollGame(mDollDetailBean.getId());
                rxDialogTurn.cancelCountDown();
                rxDialogTurn.cancel();
            }
        });

        rxDialogTurn.setOnCountDownCompleteLister(new RxDialogSureCancel.OnCountDownCompleteLister() {
            @Override
            public void onComplete() {
                //5秒后，取消排队
                dolNextGamePlayerEventSubscribe(false);
                mBtnStart.setVisibility(View.VISIBLE);
                mBtnAppointment.setVisibility(View.GONE);
                setOperateUi(false);
                rxDialogTurn.cancelCountDown();
                rxDialogTurn.cancel();
            }
        });
        rxDialogTurn.show();
    }

    private void handleOnDeviceStatusChange(SocketDeviceStatusBean bean) {
        Timber.d("handleOnDeviceStatusChange:" + bean.getDevice_status());
        if (isFinishing()) return;
        if (null == bean) return;
        if (bean.getDevice_status() == Constant.DEVICE_STATUS_PLAYING) {
            if (null != bean.getPlayer()) {
                tvTime.setVisibility(View.VISIBLE);
                tvUserName.setText(bean.getPlayer().getNickname());
                Glide.with(this).load(bean.getPlayer().getAvatar()).into(avatarImage);
                avatarLayout.setVisibility(View.VISIBLE);
                //修改为预约
                mBtnAppointment.setVisibility(View.VISIBLE);
            }
        } else if (bean.getDevice_status() == Constant.DEVICE_STATUS_FREE) {
            mBtnAppointment.setVisibility(View.GONE);
            setOperateUi(false);
            tvTime.setVisibility(View.GONE);
            if (null != bean.getGame_record() && bean.getGame_record().getId() == mGameRecordId) {
                if (Constant.OPERATE_RESULT_WITHOUT_OPERATE == bean.getGame_record().getOperate_result()) {
                    Timber.d("没有操作");
                } else if (Constant.OPERATE_RESULT_SUCCESS == bean.getGame_record().getOperate_result()) {
                    Timber.d("操作成功");
                    doSuccessDialog();
                    doOnlookerPlayer();                 //切回围观者模式
                    mArtqiyiCommandManager.disConnect();
                    ILVLiveManager.getInstance().quitRoom(null);
                } else if (Constant.OPERATE_RESULT_FAIL == bean.getGame_record().getOperate_result()) {
                    Timber.d("操作失败");
                    doFailDialog();
                    doOnlookerPlayer();                 //切回围观者模式
                    mArtqiyiCommandManager.disConnect();
                    ILVLiveManager.getInstance().quitRoom(null);
                }
            }
        } else {
            avatarLayout.setVisibility(View.GONE);
            tvTime.setVisibility(View.GONE);
        }
    }

    private void handleOnLookerChange(SocketOnLookerBean bean) {
        Timber.d("handleOnLookerChange:");
        if (isFinishing()) return;
        if (null == bean) return;
        tvPeopleNum.setText(bean.getCount() + "人");
        onLookerLayout.setVisibility(bean.getCount() == 0 ? View.GONE : View.VISIBLE);
        List<String> avatars = bean.getAvatars();
        if (null != avatars) {
            if (avatars.size() == 0) {
                avatarImage1.setVisibility(View.GONE);
                avatarImage2.setVisibility(View.GONE);
                avatarImage3.setVisibility(View.GONE);
            } else if (avatars.size() == 1) {
                Glide.with(DollOperateActivity.this).load(avatars.get(0)).into(avatarImage1);
                avatarImage1.setVisibility(View.VISIBLE);
                avatarImage2.setVisibility(View.GONE);
                avatarImage3.setVisibility(View.GONE);
            } else if (avatars.size() == 2) {
                Glide.with(DollOperateActivity.this).load(avatars.get(0)).into(avatarImage1);
                Glide.with(DollOperateActivity.this).load(avatars.get(1)).into(avatarImage2);
                avatarImage1.setVisibility(View.VISIBLE);
                avatarImage2.setVisibility(View.VISIBLE);
                avatarImage3.setVisibility(View.GONE);
            } else {
                Glide.with(DollOperateActivity.this).load(avatars.get(0)).into(avatarImage1);
                Glide.with(DollOperateActivity.this).load(avatars.get(1)).into(avatarImage2);
                Glide.with(DollOperateActivity.this).load(avatars.get(2)).into(avatarImage3);
                avatarImage1.setVisibility(View.VISIBLE);
                avatarImage2.setVisibility(View.VISIBLE);
                avatarImage3.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void reLoadData() {
        super.reLoadData();
        if (null != UserInfoManager.getInstance().getUserInfoBean())
            tvCoin.setText(String.valueOf(UserInfoManager.getInstance().getUserInfoBean().getCoin()));
        if (null != mMediaManager && isSoundOn) mMediaManager.resume();
        ILVLiveManager.getInstance().onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        ILVLiveManager.getInstance().onPause();
        if (!isDetailDialogShow && null != mMediaManager) mMediaManager.pause();
    }

    @Override
    public void onBackPressed() {
        if (isGameStart) {
            doHintDialog();
            return;
        }
        super.onBackPressed();
    }

    private void doHintDialog() {
        RxDialogNormal rxDialogTurn = new RxDialogNormal(DollOperateActivity.this);//提示弹窗
        rxDialogTurn.setTitle("提示");
        rxDialogTurn.setContent("正在游戏中，不能返回");
        rxDialogTurn.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogTurn.cancel();
            }
        });
        rxDialogTurn.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnDone:
                if (!ViewClickUtil.canClick()) return;
                if (countDownTimer != null) countDownTimer.stop();
                isGameStart = false;
                setOperateBtn(false);
                mArtqiyiCommandManager.sendCommand(ArtqiyiCommandManager.CommandType.ACTION_DONE);
                break;
            case R.id.btnSwitch:
                doSwitch();
                break;
            case R.id.addBtn:
                break;
            case R.id.btnStart:
                if (!ViewClickUtil.canClick()) return;
                if (null == mDollDetailBean) return;
                //先判断游戏币够不够
                if (UserInfoManager.getInstance().getUserInfoBean().getCoin() < mDollDetailBean.getCoin()) {
                    doPayDialog();
                    return;
                }
                if (null != mDollDetailBean) mPresenter.startDollGame(mDollDetailBean.getId());
                break;
            case R.id.btnDetail:
                if (!ViewClickUtil.canClick()) return;
                if (null != mDollDetailBean) {
                    isDetailDialogShow = true;
                    startActivityForResult(new Intent(DollOperateActivity.this, OperateDetailDialogActivity.class).putExtra(Constant.KEY_MACHINE_ID, mDollDetailBean.getId())
                            .putExtra(Constant.KEY_MACHINE_DETAIL_IMAGE, mDollDetailBean.getDetail_image()), mRequestCode);
                }
                break;

            case R.id.imageCoin:
                if (ConfigManager.getInstance().getClosePay()) return;
                if (ViewClickUtil.canClick()) mPresenter.getCoinBuy();
                break;

            case R.id.btnAppointment:
                if (null == mDollDetailBean) return;
                if (UserInfoManager.getInstance().getUserInfoBean().getCoin() < mDollDetailBean.getCoin()) {
                    doPayDialog();
                    return;
                }
                dolNextGamePlayerEventSubscribe(true);
                mBtnAppointment.setVisibility(View.GONE);
                mBtnQueuing.setVisibility(View.VISIBLE);
                break;
            case R.id.btnQueuing:
                dolNextGamePlayerEventSubscribe(false);
                mBtnAppointment.setVisibility(View.VISIBLE);
                mBtnQueuing.setVisibility(View.GONE);
                break;
            case R.id.imageSound:
                if (isSoundOn && null != mMediaManager) mMediaManager.pause();
                if (!isSoundOn && null != mMediaManager) mMediaManager.resume();
                isSoundOn = !isSoundOn;
                Glide.with(this).load(isSoundOn ? R.mipmap.btn_operate_sound_open : R.mipmap.btn_operate_sound_close).into(imageSound);
                break;

            default:

                break;
        }
    }

    private void doSwitch() {
        isSwitch = !isSwitch;
        if (isOnlookMode) {
            //围观模式

            mOnLookerVideoViewFront.setVisibility(isSwitch ? View.GONE : View.VISIBLE);
        } else {
            //玩家模式
            mLiveVideoViewFont.setVisibility(isSwitch ? View.GONE : View.VISIBLE);
        }
    }

    //返回详情界面是否关闭的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == mRequestCode) isDetailDialogShow = false;
    }

    private void getDollDetail() {
        if (null != mDollBean) mPresenter.getDollDetail(mDollBean.getId());
    }

    //连麦模式
    private void joinRoom(String roomId) {
        if (TextUtils.isEmpty(roomId)) return;
        if (ConfigManager.getInstance().getConfigBean() == null) return;
        if (UserInfoManager.getInstance().getUserInfoBean() == null) return;
        //设置流地址是测试环境
        mArtqiyiPlayManager.setTestEnv(TextUtils.equals(Constant.DOLL_ENV_TEST, ConfigManager.getInstance().getConfigBean().getDoll_env()));
        mArtqiyiPlayManager.loginRoom(roomId, String.valueOf(UserInfoManager.getInstance().getUserInfoBean().getId()),
                UserInfoManager.getInstance().getUserInfoBean().getVideo_token(), new ArtqiyiPlayManager.LoginCallback() {
                    @Override
                    public void onLoginSuccess() {
                        Timber.d("登录成功");
                        //播放视频
                        playOnlooker();
                    }

                    @Override
                    public void onLoginFail(String msg) {
                        Timber.d("工控板登录失败" + msg);
                        if (null != progressLayout) progressLayout.setVisibility(View.VISIBLE);
                        isGameStart = false;
                        Toast.makeText(DollOperateActivity.this, "视频加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //播放围观模式视频
    public void doOnlookerPlayer() {
        isSwitch = false;
        isOnlookMode = true;
        mArtqiyiPlayManager.resumeOnlookerPlayFront();
        mArtqiyiPlayManager.resumeOnlookerPlaySide();
        mOnLookerVideoViewFront.setVisibility(View.VISIBLE);
        mLiveVideoLayout.setVisibility(View.INVISIBLE);
        mOnLookerVideoLayout.setVisibility(View.VISIBLE);

        mArtqiyiPlayManager.stopLivePlayFront();
        mArtqiyiPlayManager.stopLivePlaySide();
    }

    //播放玩家模式视频
    public void doLivePlayer() {
        isSwitch = false;
        isOnlookMode = false;
        mLiveVideoViewFont.setVisibility(View.VISIBLE);
        mLiveVideoLayout.setVisibility(View.VISIBLE);

        mArtqiyiPlayManager.startLivePlayFront(mLiveVideoViewFont, new ArtqiyiPlayManager.OnPlayListener() {
            @Override
            public void onPlayLoading() {
                Timber.d("onPlayLoading");
                mOnLookerVideoLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mOnLookerVideoLayout.setVisibility(View.INVISIBLE);
                    }
                }, 1000);
            }

            @Override
            public void onPlaySuccess() {
                Timber.d("onPlaySuccess");

            }

            @Override
            public void onPlayFail(String msg) {
                Timber.d("onPlayFail");
            }
        });
        mArtqiyiPlayManager.startLivePlaySide(mLiveVideoViewSide, null);

        mArtqiyiPlayManager.pauseOnlookerPlayFront();
        mArtqiyiPlayManager.pauseOnlookerPlaySide();
    }

    private void playOnlooker() {
        mArtqiyiPlayManager.startOnlookerPlayFront(mOnLookerVideoViewFront, new ArtqiyiPlayManager.OnPlayListener() {
            @Override
            public void onPlayLoading() {
                Timber.d("onPlayLoading");
            }

            @Override
            public void onPlaySuccess() {
                Timber.d("onPlaySuccess");
                if (null != progressLayout) progressLayout.setVisibility(View.GONE);
            }

            @Override
            public void onPlayFail(String msg) {
                Timber.d("onPlayFail");
            }
        });
        mArtqiyiPlayManager.startOnlookerPlaySide(mOnLookerVideoViewSide, null);
    }

    private void setOperateBtn(boolean enable) {
        isCommandAble = enable;
        if (null != mBtnDone) {
            mBtnDone.setAlpha(enable ? 1 : 0.3f);
            mBtnDone.setClickable(enable);
        }
        if (null != mBtnUp) {
            mBtnUp.setAlpha(enable ? 1 : 0.3f);
            mBtnUp.setClickable(enable);
        }
        if (null != mBtnLeft) {
            mBtnLeft.setAlpha(enable ? 1 : 0.3f);
            mBtnLeft.setClickable(enable);
        }
        if (null != mBtnDown) {
            mBtnDown.setAlpha(enable ? 1 : 0.3f);
            mBtnDown.setClickable(enable);
        }
        if (null != mBtnRight) {
            mBtnRight.setAlpha(enable ? 1 : 0.3f);
            mBtnRight.setClickable(enable);
        }
    }

    @Override
    public void onDestroy() {
        if (null != mMediaManager) mMediaManager.release();
        if (null != mDollBean)
            mPresenter.enterOrExitRoom(mDollBean.getId(), Constant.GAME_ACTION_EXIT);
        if (null != mSocket) {
            //取消订阅
            dolNextGamePlayerEventSubscribe(false);
            mSocket.disconnect();
            mSocket.off(Socket.EVENT_CONNECT, onConnect);
            mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
            mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
            mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectTimeout);
            mSocket.off("machine.status.changed", onDeviceStatusChange);
            mSocket.off("spectators.changed", onLookerChange);
            mSocket.off("game.next.turn", onNextGamePlayer);
        }

        if (countDownTimer != null) {
            countDownTimer.stop();
            countDownTimer = null;
        }

        mArtqiyiPlayManager.onDestroy();
        mLiveVideoViewFont.onDestroy();
        mLiveVideoViewSide.onDestroy();
        mOnLookerVideoViewFront.onDestroy();
        mOnLookerVideoViewSide.onDestroy();

        mArtqiyiCommandManager.onDestroy();

        if (null != mAnimationDrawable) {
            mAnimationDrawable.stop();
            mAnimationDrawable = null;
        }

        ILVLiveManager.getInstance().onDestory();
        super.onDestroy();
    }

    //获得娃娃机详情成功
    @Override
    public void onGetDollDetailSuccess(DollDetailBean bean) {
        if (isFinishing()) return;
        if (null == bean) return;
        mDollDetailBean = bean;
        if (null != mBtnStart)
            mBtnStart.setText(String.format(getString(R.string.operate_coin_every_time), String.valueOf(bean.getCoin())));
        if (null != mBtnAppointment)
            mBtnAppointment.setText(String.format(getString(R.string.operate_coin_every_time), String.valueOf(bean.getCoin())));
        if (bean.getDevice_status() == Constant.DEVICE_STATUS_PLAYING) {
            if (null != bean.getPlayer()) {
                tvUserName.setText(bean.getPlayer().getNickname());
                Glide.with(this).load(bean.getPlayer().getAvatar()).into(avatarImage);
                avatarLayout.setVisibility(View.VISIBLE);
            }
        }
        mBtnAppointment.setVisibility((bean.getDevice_status() == Constant.DEVICE_STATUS_FREE && bean.getQueue_length() == 0) ? View.GONE : View.VISIBLE);
    }

    //获得娃娃机详情失败
    @Override
    public void onGetDollDetailFail(String msg) {
        Timber.d(msg);
    }

    //娃娃机开始游戏成功
    @Override
    public void onStartDollGameSuccess(GameResultRespone gameResultRespone) {
        if (isFinishing()) return;
        if (null == gameResultRespone) return;

        if (gameResultRespone.getCode() == 1001) {
            //游戏币不足，需要充值
            showToast(gameResultRespone.getMessage());
        } else if (gameResultRespone.getCode() == 1002) {
            //有人在玩，需要预约排队
            dolNextGamePlayerEventSubscribe(true);
            mBtnQueuing.setVisibility(View.VISIBLE);
        } else {
            GameRecordBean bean = gameResultRespone.getData();
            if (null != bean) {
                isGameStart = true;
                doLivePlayer();
                commandConnect(bean.getAssign_info().getWs_url());
                dolNextGamePlayerEventSubscribe(true);
                mGameRecordId = bean.getId();

                doReadyDialog();
                UserInfoManager.getInstance().getUserInfoBean().setCoin(UserInfoManager.getInstance().getUserInfoBean().getCoin() - mDollDetailBean.getCoin());
                if (null != tvCoin)
                    tvCoin.setText(String.valueOf(UserInfoManager.getInstance().getUserInfoBean().getCoin()));
                tvTime.setVisibility(View.VISIBLE);
                mBtnQueuing.setVisibility(View.GONE);
                setOperateUi(true);
                setCountdown(bean.getAssign_info().getTime());
                setOperateBtn(true);
            }
        }
    }

    //websocket连接
    private void commandConnect(String url) {
        mArtqiyiCommandManager.connect(url, new ArtqiyiCommandManager.ConnectCallback() {
            @Override
            public void onConnectSuccess() {
                Timber.d("websocket连接成功");
            }

            @Override
            public void onConnectClose() {
                Timber.d("websocket连接关闭");
            }
        });
    }

    private void doReadyDialog() {
        mImageReadyGo.setVisibility(View.VISIBLE);
        if (null == mAnimationDrawable)
            mAnimationDrawable = (AnimationDrawable) mImageReadyGo.getDrawable();
        mAnimationDrawable.start();
        mImageReadyGo.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mImageReadyGo != null) mImageReadyGo.setVisibility(View.GONE);
                mAnimationDrawable.stop();
                mAnimationDrawable = null;
            }
        }, 1000);
    }

    private void setOperateUi(boolean isPlay) {
        startLayout.setVisibility(isPlay ? View.GONE : View.VISIBLE);
        operateLayout.setVisibility(isPlay ? View.VISIBLE : View.GONE);
        avatarLayout.setVisibility(isPlay ? View.VISIBLE : View.GONE);
    }

    //娃娃机开始游戏失败
    @Override
    public void onStartDollGameFail(String msg) {
        if (null != startLayout) startLayout.setVisibility(View.VISIBLE);
        if (null != operateLayout) operateLayout.setVisibility(View.GONE);
        showToast(msg);
    }

    //娃娃币购买成功
    @Override
    public void onCoinBuySuccess(List<CoinBuyBean> beans) {
        if (isFinishing()) return;
        if (null == beans || beans.size() == 0)
            Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
        if (null != beans && beans.size() != 0) doDialog(beans);
    }

    @Override
    public void onCoinBuyFail(String msg) {
        if (isFinishing()) return;
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void doDialog(List<CoinBuyBean> beans) {
        RxDialogList rxDialogList = new RxDialogList(this);//提示弹窗
        rxDialogList.getTitleView().setText("充娃娃币");
        rxDialogList.setData(beans);
        rxDialogList.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogList.cancel();
            }
        });
        rxDialogList.setOnListItemClick(new RxDialogList.OnClickListener() {
            @Override
            public void OnListItemClick(CoinBuyBean bean) {
                PayDialogManager.getInstance().getPay(bean);
                rxDialogList.cancel();
            }
        });
        rxDialogList.show();
    }

    /*操作成功*/
    @Override
    public void onOperateSuccess(int action) {
        if (isFinishing()) return;
        if (action == ArtqiyiConstant.ACTION_DONE) {
            if (countDownTimer != null) countDownTimer.stop();
            setOperateBtn(false);
        }
    }

    /*操作失败*/
    @Override
    public void onOperateFail(String msg, int action) {
        if (action == ArtqiyiConstant.ACTION_DONE) setOperateBtn(true);
    }

    //弹出失败对话框
    private void doFailDialog() {
        RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(DollOperateActivity.this);//提示弹窗
        rxDialogSureCancel.setRxDialogResult(RxDialogSureCancel.RxDialogResult.FAIL);
        rxDialogSureCancel.setCancel("休息一下");
        rxDialogSureCancel.setSure("再抓一次");
        rxDialogSureCancel.setCountDown();
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mDollDetailBean) mPresenter.startDollGame(mDollDetailBean.getId());
                if (isFinishing()) return;
                rxDialogSureCancel.cancelCountDown();
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dolNextGamePlayerEventSubscribe(false);
                if (isFinishing()) return;
                rxDialogSureCancel.cancelCountDown();
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.setOnCountDownCompleteLister(new RxDialogSureCancel.OnCountDownCompleteLister() {
            @Override
            public void onComplete() {
                //5秒后，取消排队
                dolNextGamePlayerEventSubscribe(false);
                if (isFinishing()) return;
                rxDialogSureCancel.cancelCountDown();
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.show();
    }

    //弹出成功对话框
    private void doSuccessDialog() {
        RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(DollOperateActivity.this);//提示弹窗
        rxDialogSureCancel.setRxDialogResult(RxDialogSureCancel.RxDialogResult.SUCCESS);
        rxDialogSureCancel.setCancel("继续抓");
        rxDialogSureCancel.setSure("去领取");
        rxDialogSureCancel.setCountDown();
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //5秒后，取消排队
                dolNextGamePlayerEventSubscribe(false);
                startActivity(new Intent(DollOperateActivity.this, WebViewActivity.class).putExtra(Constant.KEY_MINE_WEBVIEW_TYPE, Constant.MINE_MYWAWA));
                if (isFinishing()) return;
                rxDialogSureCancel.cancelCountDown();
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mDollDetailBean) mPresenter.startDollGame(mDollDetailBean.getId());
                if (isFinishing()) return;
                rxDialogSureCancel.cancelCountDown();
                rxDialogSureCancel.cancel();
            }
        });

        rxDialogSureCancel.setOnCountDownCompleteLister(new RxDialogSureCancel.OnCountDownCompleteLister() {
            @Override
            public void onComplete() {
                //5秒后，取消排队
                dolNextGamePlayerEventSubscribe(false);
                if (isFinishing()) return;
                rxDialogSureCancel.cancelCountDown();
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.show();
    }

    //弹出支付对话框
    private void doPayDialog() {
        RxDialogPay rxDialogPay = new RxDialogPay(DollOperateActivity.this);//提示弹窗
        rxDialogPay.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getCoinBuy();
                rxDialogPay.cancel();
            }
        });
        rxDialogPay.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogPay.cancel();
            }
        });
        rxDialogPay.show();
    }

    //设置倒计时
    private void setCountdown(int time) {
        if (time == 0) return;
        if (countDownTimer != null) countDownTimer.stop();
        countDownTimer = Rx2Timer.builder()
                .initialDelay(0) //default is 0
                .period(1) //default is 1
                .take(time) //default is 60
                .unit(TimeUnit.SECONDS) // default is TimeUnit.SECONDS
                .onEmit(count -> {
                    tvTime.setText(count + "s");
                })
                .onError(e -> tvTime.setText("0s"))
                .onComplete(() -> {
                    isGameStart = false;
                    tvTime.setText("0s");
                    setOperateBtn(false);
                    mPresenter.doOperateDone(mDollBean.getId());
                })
                .build();
        countDownTimer.start();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!isCommandAble) return false;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                doOnTouch(v.getId());
                break;
            case MotionEvent.ACTION_MOVE:

                break;
            case MotionEvent.ACTION_UP:
                stopOnTouch();
                break;
        }
        return false;
    }

    private void doOnTouch(int id) {
        switch (id) {
            case R.id.btnUp:
                mArtqiyiCommandManager.sendCommand(isSwitch ? ArtqiyiCommandManager.CommandType.ACTION_LEFT : ArtqiyiCommandManager.CommandType.ACTION_BACK);
                break;
            case R.id.btnLeft:
                mArtqiyiCommandManager.sendCommand(isSwitch ? ArtqiyiCommandManager.CommandType.ACTION_FORWARD : ArtqiyiCommandManager.CommandType.ACTION_LEFT);
                break;
            case R.id.btnDown:
                mArtqiyiCommandManager.sendCommand(isSwitch ? ArtqiyiCommandManager.CommandType.ACTION_RIGHT : ArtqiyiCommandManager.CommandType.ACTION_FORWARD);
                break;
            case R.id.btnRight:
                mArtqiyiCommandManager.sendCommand(isSwitch ? ArtqiyiCommandManager.CommandType.ACTION_BACK : ArtqiyiCommandManager.CommandType.ACTION_RIGHT);
                break;
        }
    }

    private void stopOnTouch() {
        mArtqiyiCommandManager.commandStop();
    }
}
